import sysConfig from "@/config";
const tool = {}

// 获取本地资源文件
tool.getAssetsImages = (url) => {
    return new URL(`/src/assets/${url}`, import.meta.url).href;
}

/* localStorage */
tool.data = {
    set(key, data, datetime = 0) {
        //加密
        if(sysConfig.LS_ENCRYPTION === "AES"){
            data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
        }
        let cacheValue = {
            content: data,
            datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
        }
        // console.log(cacheValue, JSON.stringify(cacheValue))
        return localStorage.setItem(key, JSON.stringify(cacheValue))
    },
    get(key) {
        try {
            const value = JSON.parse(localStorage.getItem(key))
            if (value) {
                let nowTime = new Date().getTime()
                if (nowTime > value.datetime && value.datetime != 0) {
                    localStorage.removeItem(key)
                    return null;
                }
                //解密
                if(sysConfig.LS_ENCRYPTION == "AES"){
                    value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
                }
                return value.content
            }
            return null
        } catch (err) {
            return null
        }
    },
    remove(key) {
        return localStorage.removeItem(key)
    },
    clear() {
        return localStorage.clear()
    }
}

/*cookie*/
tool.cookie = {
    set(name, value, config={}) {
        var cfg = {
            expires: null,
            path: null,
            domain: null,
            secure: false,
            httpOnly: false,
            ...config
        }
        var cookieStr = `${name}=${escape(value)}`
        if(cfg.expires){
            var exp = new Date()
            exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
            cookieStr += `;expires=${exp.toGMTString()}`
        }
        if(cfg.path){
            cookieStr += `;path=${cfg.path}`
        }
        if(cfg.domain){
            cookieStr += `;domain=${cfg.domain}`
        }
        document.cookie = cookieStr
    },
    get(name){
        var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))
        if(arr != null){
            return unescape(arr[2])
        }else{
            return null
        }
    },
    remove(name){
        var exp = new Date()
        exp.setTime(exp.getTime() - 1)
        document.cookie = `${name}=;expires=${exp.toGMTString()}`
    }
}

// --- 数据操作 ---
tool.array = {
    /**
     * 在数组内查找指定元素，查询到数据返回数组元素对应的索引，查询不到返回 -1
     * @param arr       数组， 如：[1,2,3,4,5,6]
     * @param needFind  要查找的元素，如 5
     * @returns {number}
     */
    arrayIndexOf(arr, needFind) {
        var index = -1;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] === needFind) {
                index = i;
                return i;
            }
        }
        return index;
    },
    // 数组合并
    arrayConcat() {
        var tmpArr = [];
        for (let i = 0; i < arguments.length; i++) {
            tmpArr = tmpArr.concat(arguments[i]);
        }
        return tmpArr;
    },
    // 删除数组最后一个
    truncate(arr) {
        let callback = [];
        for(let i = 0; i < arr.length-1;i++){
            callback.push(arr[i]);
        }
        return callback;
    },
    /**
     * 将资源对象中的key名与目标对象一致的key值，赋值进去，不改标目标对象的对象结构
     * @param target 目标对象
     * @param source 资源对象
     */
    cloneExistKey(target, source) {
        Object.keys(target).forEach((key) => {
            if(source[key] !== undefined) {
                target[key] = source[key]
            }
        });
        return target
    },
    /**
     * 重建数组索引
     * 按一个指定的键名重新索引一个数组，可以用 index 方法。输入的数组应该是多维数组或者是一个对象数组。 键名（第二个参数）可以是子数组的键名、对象的属性名
     * @param arr
     * @param key
     * @returns {*[]}
     */
    index(arr, key) {
        let callback = [];
        for(let i = 0; i < arr.length;i++){
            callback[arr[i][key]] = arr[i]
        }
        return callback;
    },
    /**
     * 删除某个值
     * @param obj
     * @param key
     */
    removeByKey: function(obj, key) {
        delete obj[key];
    },
    /**
     * 指定数组，遍历子级，指定key和value的字段名，组成新的数组
     * @param array
     * @param from
     * @param to
     * @param group
     * @returns {*[]}
     *
     * @example
     *
     * // 示例数据
     * const treeData = [
     *     {
     *         id: 1,
     *         name: 'Node 1',
     *         children: [
     *             { id: 2, name: 'Node 1.1', children: [] },
     *             {
     *                 id: 3,
     *                 name: 'Node 1.2',
     *                 children: [
     *                     { id: 4, name: 'Node 1.2.1', children: [] }
     *                 ]
     *             }
     *         ]
     *     },
     *     {
     *         id: 5,
     *         name: 'Node 2',
     *         children: [
     *             { id: 6, name: 'Node 2.1', children: [] }
     *         ]
     *     }
     * ];
     *
     * // 调用函数：提取 id 和 name
     * const result = map(treeData, 'id', 'name');
     *
     * // 输出
     * [
     *     { name: 1, id: 'Node 1' },
     *     { name: 2, id: 'Node 1.1' },
     *     { name: 3, id: 'Node 1.2' },
     *     { name: 4, id: 'Node 1.2.1' },
     *     { name: 5, id: 'Node 2' },
     *     { name: 6, id: 'Node 2.1' }
     * ]
     */
    map: function (array, from, to, group = 'children') {
        const result = [];
        // 递归遍历树结构
        function traverse(nodes) {
            nodes.forEach(node => {
                // 提取指定的字段并存入结果数组
                result.push({ [to]: node[from], [from]: node[to] });
                // 如果有子节点，递归调用
                if (node[group] && node[group].length > 0) {
                    traverse(node[group]);
                }
            });
        }
        traverse(array); // 开始递归
        return result;
    },
    /**
     * 提取特定字段组成数组
     * @param array
     * @param field
     * @param group
     * @returns {*[]}
     *
     * @example
     *
     * // 示例数据
     * const treeData = [
     *   {
     *     id: 1,
     *     name: "Node 1",
     *     children: [
     *       { id: 2, name: "Node 1.1" },
     *       {
     *         id: 3,
     *         name: "Node 1.2",
     *         children: [{ id: 4, name: "Node 1.2.1" }]
     *       }
     *     ]
     *   },
     *   {
     *     id: 5,
     *     name: "Node 2",
     *     children: [{ id: 6, name: "Node 2.1" }]
     *   }
     * ];
     *
     * // 使用 getColumn 函数提取 id 字段
     * const ids = getColumn(treeData, 'id');
     * console.log(ids); // [1, 2, 3, 4, 5, 6]
     *
     */
    getColumn: function (array, field, group = 'children') {
        let result = [];
        const extractField = (nodes) => {
            nodes.forEach(node => {
                if (node[field] !== undefined) {
                    result.push(node[field]);
                }
                if (node[group] && Array.isArray(node[group])) {
                    extractField(node[group]); // 递归处理子节点
                }
            });
        };

        extractField(array);
        return result;
    },
    /**
     * 递归过滤树形数据，保留符合条件的节点
     * @param tree
     * @param allowedParams  允许的参数数组，如果是允许ID的话，这里就是['id1', 'id2']
     * @param allowedField   允许的字段名，如id
     * @param group
     * @returns {*}
     *
     * @example
     * // 示例数据
     * const treeData = [
     *   {
     *     id: 1,
     *     path: '/business',
     *     name: 'Business',
     *     title: '业务管理',
     *     component: 'layouts/BasicLayout',
     *     redirect: '/business/postage',
     *     meta: { showMenu: true, icon: 'FormOutlined', type: 'menu', role: ['admin'], breadcrumb: ['业务管理'] },
     *     children: [
     *       { id: 1001, path: '/business/postage', name: 'BusinessPostage', title: '资费管理', component: 'views/business/postage/index', meta: {} },
     *       { id: 1002, path: '/business/station', name: 'BusinessStation', title: '场站管理', component: 'views/business/station/index', meta: {} },
     *       { id: 1003, path: '/business/charging', name: 'BusinessCharging', title: '充电桩详情', component: 'views/business/charging/index', meta: {} },
     *       { id: 1004, path: '/business/operators', name: 'BusinessOperators', title: '运营商', component: 'views/business/operators/index', meta: {} }
     *     ]
     *   },
     *   {
     *     id: 2,
     *     path: '/user',
     *     name: 'User',
     *     title: '用户管理',
     *     component: 'layouts/UserLayout',
     *     children: [
     *       { id: 2001, path: '/user/list', name: 'UserList', title: '用户列表', component: 'views/user/list/index', meta: {} },
     *       { id: 2002, path: '/user/card', name: 'UserCard', title: '用户卡绑定', component: 'views/user/card/index', meta: {} }
     *     ]
     *   }
     * ];
     *
     * const allowedIds = ['1', '2'];
     *
     * // 使用 filterTree 函数
     * const filteredTree = treeUtils.filterTree(treeData, allowedIds, 'id');
     * console.log(JSON.stringify(filteredTree, null, 2));
     */
    filterTree: function (tree, allowedParams, allowedField = 'id', group = 'children') {
        // console.log(tree)
        // console.log(allowedPath)
        return tree
            .map(node => {
                const filteredNode = { ...node }; // 浅拷贝当前节点
                if (filteredNode[group] && Array.isArray(filteredNode[group])) {
                    // 递归处理子节点
                    filteredNode[group] = this.filterTree(filteredNode[group], allowedParams, allowedField, group);
                }
                // 判断当前节点是否符合条件或子节点不为空
                if (allowedParams.includes(filteredNode[allowedField]) || (filteredNode[group] && filteredNode[group].length > 0)) {
                    return filteredNode;
                }
                return null; // 排除不符合条件的节点
            })
            .filter(node => node !== null); // 去掉空节点
    },
    /**
     * 遍历树数据，获取每组中checked为true的指定字段（如：ID）集合
     * @param treeData
     * @param field 指定字段名
     * @returns {*[]}
     *
     * @example $TOOL.array.getCheckedKeysByTree(treeData, 'title')
     */
    getCheckedKeysByTree(treeData, field = 'id') {
        const checkedIds = [];
        treeData.forEach(item => {
            if (item.children && item.children.length > 0) {
                item.children.forEach(child => {
                    if (child.checked) {
                        checkedIds.push(child[field]);
                    }
                });
            }
        });
        return checkedIds;
    },
    /**
     * 要遍历一个对象（如 params），并移除其中值为空的键，
     * @param obj
     * @returns {{[p: string]: unknown}}
     */
    cleanParams(obj) {
        return Object.fromEntries(
            Object.entries(obj).filter(([_, value]) => value !== null && value !== undefined && value !== '')
        );
    }
}

// --- 日期时间 ---
tool.time = {
    now(type, addTime) {
        var dateObj = new Date();
        var cTime = dateObj.getTime();
        if (addTime) {
            cTime += addTime;
        }
        if (!type) {
            type = 'number';
        }
        if (type === 'number') {
            return cTime;
        } else if (type === 'str') {
            return this.toDate(cTime / 1000, 'str');
        } else if (type === 'Y-m-d') {
            return this.toDate(cTime / 1000, 'Y-m-d');
        } else if (type === 'array') {
            return this.toDate(cTime / 1000, 'array');
        }
    },
    // 时间戳转 YY-mm-dd HH:ii:ss
    toDate(timeStamp, returnType) {
        timeStamp = parseInt(timeStamp);
        var date = new Date();
        if (timeStamp < 90000000000) {
            date.setTime(timeStamp * 1000);
        } else {
            date.setTime(timeStamp);
        }
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        if (returnType === 'str') {
            return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
        }else if (returnType === 'Y-m-d') {
            return y + '-' + m + '-' + d;
        }else if (returnType === 'Y-m-d H:i') {
            return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
        }
        return [y, m, d, h, minute, second];
    },
    // 字符串转时间戳
    toTimeStamp(timeStamp) {
        var reg = /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
        var res = timeStamp.match(reg);
        var year = 0,
            month = 0,
            day = 0,
            h = 0,
            i = 0,
            s = 0;
        if (res == null) {
            var reg2 = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
            var res2 = timeStamp.match(reg2);
            if (res2 == null) {
                console.log('时间格式错误 E001');
                return false;
            }
            year = parseInt(res2[3]);
            month = parseInt(res2[1]);
            day = parseInt(res2[2]);
            h = parseInt(res2[4]);
            i = parseInt(res2[5]);
            s = parseInt(res2[6]);
        } else {
            year = parseInt(res[1]);
            month = parseInt(res[2]);
            day = parseInt(res[3]);
            h = parseInt(res[4]);
            i = parseInt(res[5]);
            s = parseInt(res[6]);
        }
        if (year < 1000) {
            console.log('时间格式错误');
            return false;
        }
        if (h < 0 || h > 24) {
            console.log('时间格式错误');
            return false;
        }
        if (i < 0 || i > 60) {
            console.log('时间格式错误');
            return false;
        }
        if (s < 0 || s > 60) {
            console.log('时间格式错误');
            return false;
        }
        return Date.parse(new Date(year, month - 1, day, h, i, s));
    },
    // 根据时间戳计算多少分钟/小时/天之前
    fromTime(time) {
        if (time < 90000000000) {
            time *= 1000;
        }
        var timer = new Date().getTime() - time;
        timer = parseInt(timer / 1000);
        if (timer < 180) {
            return '刚刚';
        } else if (timer >= 180 && timer < 3600) {
            return parseInt(timer / 60) + '分钟前';
        } else if (timer >= 3600 && timer < 86400) {
            return parseInt(timer / 3600) + '小时前';
        } else if (timer >= 86400 && timer < 2592000) {
            return parseInt(timer / 86400) + '天前';
        } else {
            return this.toDate(time, 'str');
        }
    },
}

tool.string = {
    isHave(string,search) {
        return string.includes(search);
    },
    // 2数之间的随机数
    random(min, max) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * min + 1, 10);
            case 2:
                return parseInt(Math.random() * (max - min + 1) + min, 10);
            default:
                return 0;
        }
    },
    // UUID
    uuid(len) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        if (len) {
            for (i = 0; i < len; i++) {
                uuid[i] = chars[0 | Math.random() * chars.length];
            }
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    },
    getPriority(val) {
        const options = [
            { value: 'high', label: '高' },
            { value: 'medium', label: '中' },
            { value: 'low', label: '低' },
            { value: 'none', label: '无' },
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    }
}

tool.crmOrder = {
    /**
     * 获取销售渠道
     * @param val
     * @returns {string|*|[{label: string, value: number},{label: string, value: number},{label: string, value: number}]}
     */
    getChannel(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '网店', value: 1 },
            { label: '门店', value: 2 }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },

    /**
     * 获取订单状态
     * @param val
     * @returns {[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},null]|string|*}
     */
    getStatus(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '待付款', value: 1 },
            { label: '待发货', value: 2 },
            { label: '已发货', value: 3 },
            { label: '已关闭', value: 4 },
            { label: '售后中', value: 5 },
            { label: '售后成功', value: 6 }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },
    /**
     * 获取配送方式
     * @param val
     * @returns {[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number}]|string|*}
     */
    getDelivery(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '快递', value: 1 },
            { label: '同城配送', value: 2 },
            { label: '自提', value: 3 }
        ]
        if(val === 99) {
            // 选择配送方式，去掉第一个
            delete options[0]
        }else{
            if(val) {
                const item = options.find(item => item.value === val)
                return item ? item.label : '--'
            }
        }
        return options
    },
    /**
     * 获取售后状态
     * @param val
     * @returns {string|*|[{label: string, value: number},{label: string, value: number},{label: string, value: number}]}
     */
    getRefunds(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '售后中', value: 1 },
            { label: '售后结束', value: 2 }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },
    /**
     * 获取支付方式
     * @param val
     * @returns {[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},null,null,null,null,null,null,null]|string|*}
     */
    getPayment(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '微信支付', value: 1 },
            { label: '支付宝-商家扫', value: 2 },
            { label: '支付宝-用户付', value: 3 },
            { label: '花呗支付', value: 4 },
            { label: '货到付款', value: 5 },
            { label: '礼品卡付款', value: 6 },
            { label: '现金', value: 7 },
            { label: '银行卡付款', value: 8 },
            { label: '对公转帐', value: 9 },
            { label: '数币支付', value: 10 },
            { label: '云闪付支付', value: 11 }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },
    /**
     * 获取订单来源
     * @param val
     * @returns {[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},null,null,null,null,null,null,null,null,null,null,null]|string|*}
     */
    getSource(val) {
        const options = [
            { label: '全部', value: 0 },
            { label: '微信小程序', value: 1 },
            { label: '微商城', value: 2 },
            { label: '浏览器', value: 3 },
            { label: '腾讯QQ', value: 4 },
            { label: '微博', value: 5 },
            { label: '快手', value: 6 },
            { label: '天猫', value: 7 },
            { label: '淘宝', value: 8 },
            { label: '拼多多', value: 9 },
            { label: '京东', value: 10 },
            { label: '商家自有APP', value: 11 },
            { label: '微信视频号', value: 12 },
            { label: '小红书', value: 13 },
            { label: '建行生活APP', value: 14 },
            { label: '其他', value: 15 },
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },
    /**
     * 获取快递公司
     * @param val
     * @returns {[{label: string, value: string},{label: string, value: string},{label: string, value: string},{label: string, value: string},{label: string, value: string},null,null,null,null,null,null,null,null,null,null]|string|*}
     */
    getExpress(val) {
        const options = [
            { "label": "顺丰速运", "value": "SF" },
            { "label": "申通快递", "value": "STO" },
            { "label": "圆通速递", "value": "YTO" },
            { "label": "中通快递", "value": "ZTO" },
            { "label": "百世快递", "value": "HTKY" },
            { "label": "韵达快递", "value": "YD" },
            { "label": "邮政快递包裹", "value": "YZPY" },
            { "label": "天天快递", "value": "HHTT" },
            { "label": "京东快递", "value": "JD" },
            { "label": "德邦物流", "value": "DBL" },
            { "label": "EMS", "value": "EMS" },
            { "label": "宅急送", "value": "ZJS" },
            { "label": "优速快递", "value": "UC" },
            { "label": "快捷快递", "value": "FAST" },
            { "label": "其他", "value": "OTHER" }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    }
}

tool.planOrder = {
    /**
     * 获取生产订单状态
     * @param val
     * @returns {[{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},{label: string, value: number},null]|string|*}
     */
    getStatus(val) {
        const options = [
            { value: 1, label: '已创建' },
            { value: 2, label: '待调度' },
            { value: 3, label: '已调度' },
            { value: 4, label: '进行中' },
            { value: 5, label: '暂停' },
            { value: 6, label: '完成' },
            { value: 7, label: '关闭' },
            { value: -1, label: '取消' }
        ]
        if(val) {
            const item = options.find(item => item.value === val)
            return item ? item.label : '--'
        }
        return options
    },
}

tool.test = () => {
    return 'tool test'
}

export default tool
